import Vue from 'vue';

export default {
  install(Vue) {
    Vue.directive('login', {
      inserted(el, binding) {
        el.addEventListener('click', async () => {
          const { form, api, success, error } = binding.value;

          if (!form.phone || !form.password) {
            Vue.prototype.$notify.error('请填写完整登录信息');
            return;
          }

          try {
            const res = await api(form);
            if (res.code === 200) {
              localStorage.setItem('token', res.list.token);
              localStorage.setItem('userInfo', JSON.stringify(res.list));
              success?.();
            } else {
              error?.();
            }
          } catch (err) {
            Vue.prototype.$notify.error('请求异常');
          }
        });
      }
    });
    v
  }
};